<template>
  <div class="flex items-center">
    <img v-if="value" :src="value" alt="" class="mr-5" :style="{ width: width }">
    <el-upload
      :action="uploadUrl"
      :headers="headers"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :show-file-list="false"
      :disabled="disabled"
    >
      <el-button size="small" :type="disabled ? 'info': 'primary'">{{ value ? '更改图片' : '选择图片' }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import store from '@/store'

export default {
  name: 'UploadImage',
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: 'auto'
    }
  },
  data() {
    return {
      uploadUrl: '/api-company/tools/upload-image'
    }
  },
  computed: {
    headers() {
      return {
        'token': `${store.getters.token}`
      }
    }
  },
  methods: {
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.$emit('input', res.data) // 更新v-model
      }
    },
    handleUploadError(err) {
      console.error('上传失败:', err)
      this.$message.error('图片上传失败')
    }
  }
}
</script>
